package com.study.com.study;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;

/**
 * @author sunxuejian
 * @date 2020/11/28
 */
public class Demo1 {

    public static void main(String[] args) throws Exception {

        TransportClient client = null;
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        client = TransportClient.builder().settings(settings).build();

        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.170.112"), Integer.valueOf("9300")));
        System.out.println(client);


        get2(client);

    }

    /**
     * 获取员工信息
     * @param client
     * @throws Exception
     */
    private static void get1(TransportClient client) throws Exception {
        GetResponse response = client.prepareGet("metrics_alias", "forcebot_result", "15837_forcebot.test").get();
        System.out.println(response);
        System.out.println(response.getSourceAsString());
    }

    // logger.info("index: " + parameterTool.get(TpConstant.ES_INDEX) + " type: " + parameterTool.get(TpConstant.ES_TYPE_RESULT) + " id: " + (testId + "_" + transactionId) )
    //
    private static void get2(TransportClient client) throws Exception {
        SearchResponse searchResponse = client.prepareSearch("metrics_alias").setTypes("forcebot_result")
                .setQuery(QueryBuilders.idsQuery().addIds("15839_forcebot.test")).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数，查询结果有多少对象
        System.out.println("查询结果有：" + hits.getTotalHits() + "条");
        SearchHit[] hits1 = hits.getHits();
        byte[] source = hits1[0].source();
        String s = new String(source, 0, source.length);
        System.out.println(s);


    }
}
